package com.suzhe.ymall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suzhe.ymall.product.pojo.Brand;
import com.suzhe.ymall.product.mapper.BrandMapper;
import com.suzhe.ymall.product.pojo.Category;
import com.suzhe.ymall.product.pojo.CategoryBrand;
import com.suzhe.ymall.product.service.IBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suzhe.ymall.product.service.ICategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author suzhe
 * @since 2019-07-06
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    @Autowired
    ICategoryBrandService iCategoryBrandService;
    @Transactional
    @Override
    public void saveBrand(Brand brand) {
        Integer id = brand.getId();
        brand.setUpdateTime(new Date());
        if (id == null){
            save(brand);
        }else{
            updateById(brand);
            deleteOldCategoryBrand(id);
        }
        List<Category> categories = brand.getCategories();
        List<CategoryBrand> categoryBrands = new ArrayList<>(categories.size());
        if (!categories.isEmpty()){
            categories.forEach(item -> {
                CategoryBrand categoryBrand = new CategoryBrand();
                categoryBrand.setBrandId(brand.getId());
                categoryBrand.setCategoryId(item.getId());
                categoryBrands.add(categoryBrand);
            });
        }
        iCategoryBrandService.saveBatch(categoryBrands);

    }

    private void deleteOldCategoryBrand(Integer brandId) {
        iCategoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",brandId));
    }
}
